from flask import jsonify, request

from commons.controller.base_controller import BaseController
from commons.entity.enum.response_code_enum import ResponseCodeEnum
from user_service.user.service.user_service import UserService


class UserController(BaseController):
    def __init__(self):
        self.user_service = UserService()

    def test(self):
        self.user_service.test()

        return BaseController.get_success_response(self, ResponseCodeEnum.CODE_200.code)

    def get_user_by_id(self):
        """
        根据用户ID获取用户信息。
        """
        # 从请求体解析参数
        data = request.get_json()
        user_id = data.get("userId")

        return BaseController.get_success_response(self, self.user_service.get_user_by_user_id(user_id))

    def login(self):
        """
        用户登录功能。
        通过用户ID、职位和密码验证用户身份。
        """
        data = request.get_json()
        # 获取请求中的参数
        position = data.get("position")
        user_id = data.get("userId")
        password = data.get("password")

        return BaseController.get_success_response(self, self.user_service.login(position, user_id, password))

    def get_all_users_by_id_list(self):
        """
        根据用户ID列表获取用户信息。
        """
        print("UserController get_all_users_by_id_list")
        # 从请求体解析参数
        data = request.get_json()
        user_id_list = data.get("userIdList")
        users = self.user_service.get_all_users_by_id_list(
            user_id_list)

        return jsonify([user.to_dict() for user in users])

    def update_user_by_user_id(self):
        """
        根据 UserId 更新用户信息，只能修改电话、email 和密码。
        """
        # 从请求中解析参数
        data = request.get_json()
        phone = data.get("phone")
        email = data.get("email")
        password = data.get("password")
        user_id = data.get("userId")

        # 参数验证（可以选择用更强的验证，如 marshmallow 或 pydantic）
        if not phone or not email or not password or not user_id:
            return jsonify({"error": "Missing required parameters"}), 400

        # 创建 User 实例并设置字段
        user_bean = {
            "phone": phone,
            "email": email,
            "password": password
        }

        # 调用服务层的方法进行更新
        success = self.user_service.update_user_by_user_id(user_bean, user_id)

        # 返回操作结果
        if success:
            return BaseController.get_success_response(self, ResponseCodeEnum.CODE_200.code)
        else:
            return jsonify({"error": "Update failed"}), 500